<template>
	<view class="item-card padding bg-white margin-bottom">
		<view @click="addOrder('info')">

			<view class="item-top padding-bottom-sm flex align-center justify-between solid-bottom">
				<view class="flex align-center">
					<template v-if="inOrder">
						<image class="ti-img" :src="`${$hd.baseUrl}/images/${theme}/icon-number.png`" mode="aspectFit">
						</image>
						<text class="text-gray margin-left-sm">{{dataItem.orderCode}}</text>
					</template>
					<template v-else>
						<image class="ti-img" :src="`${$hd.baseUrl}/images/icon-address.png`" mode="aspectFit"></image>
						<text class="text-gray margin-left-sm text-cut"
							style="width: 450rpx">{{dataItem.address||''}}</text>
					</template>
				</view>
				<view class="text-green" v-if="inOrder">
					{{statusLabel}}
				</view>
				<text v-else class="jl-text">{{dataItem.distance}}</text>
			</view>
			<view class="flex align-center justify-between text-lg margin-tb-sm">
				<view class="flex-sub">
					<view class="w-90 uv-line-1 text-black text-bold">{{dataItem.orderName||''}}</view>
				</view>
				<view class="color-red">
					<text class="text-sm">￥</text>
					<text class="text-bold text-xl">{{dataItem.actualMoney || dataItem.money}}</text>
				</view>
			</view>
			<view class="text-cut">
				<view class='cu-tag'>{{ dataItem.cropName }}</view>
				<view class='cu-tag' v-if="dataItem.homeworkType == 1">面积{{dataItem.area}}亩</view>
				<view class='cu-tag' v-else>重量{{dataItem.area}}吨</view>
				<view class='cu-tag' v-if="dataItem.cropAcreUsage">{{ dataItem.cropAcreUsage }}L/亩</view>
			</view>
			<view class="text-gray margin-top-sm flex" v-if="inOrder">
				<view class="flex-sub text-cut">
					地址：{{dataItem.address}}
				</view> <text class="color-blue margin-left">{{dataItem.distance||''}}</text>
			</view>

		</view>
		<view class="flex align-center justify-between margin-top-sm">
			<view class="text-gray">
				推荐作业时间：{{dataItem.dockingPeopleTime | dateOnly}}
			</view>
			<view class="color-red text-lg" v-if="!inOrder" @click.stop="addOrder('rob')">
				去抢单
			</view>
		</view>


		<view class="solid-top padding-top-sm margin-top-sm text-right" v-if="inOrder">
			<template v-if="theme == 'fs'">
				<button class="cu-btn line-gray margin-left-sm sm" @click="onReport"
					v-if="dataItem.status > 2 && dataItem.status < 5 && dataItem.status != 12">上报异常</button>
				<button class="cu-btn bg-main margin-left-sm sm" @click="reStart"
					v-if="dataItem.status == 12">继续任务</button>
				<button class="cu-btn bg-main sm margin-left-sm" @click="onSigin"
					v-if="dataItem.status == 16">到达签到</button>
				<button class="cu-btn bg-main sm margin-left-sm" @click="onUpdata"
					v-if="dataItem.status > 2 && dataItem.status < 5">进度上传</button>
				<!-- <button class="cu-btn bg-green margin-left-sm sm" @click="handlePay">去支付</button> -->
				<button class="cu-btn bg-main sm margin-left-sm" v-if="dataItem.status == 1"
					@click="robOrder">立即抢单</button>
			</template>
			<template v-else>
				<!-- <button class="cu-btn bg-red sm" v-if="dataItem.status == 1" @click="onCancel">取消订单</button> -->
				<button class="cu-btn bg-main margin-left-sm sm" v-if="dataItem.status == 1"
					@click="onEdit">修改订单</button>
				<button class="cu-btn bg-green margin-left-sm sm" @click="onReport"
					v-if="dataItem.status > 2 && dataItem.status < 5 && dataItem.status != 12">上报异常</button>
				<!-- <button class="cu-btn bg-green margin-left-sm sm" @click="handlePay">去支付</button> -->
				<button class="cu-btn bg-green margin-left-sm sm" v-if="dataItem.status == 5"
					@click="handleAuth">去审核</button>
			</template>
		</view>
	</view>
</template>

<script>
	import {
		selectDictLabel
	} from '@/utils/huida.js'
	import {
		mapGetters
	} from 'vuex'
	export default {
		// 订单列表校验
		computed: {
			...mapGetters(['theme', 'userInfo']),
			statusLabel() {
				const {status,isStatus,commentStar,exceptionType,frozenReason } = this.dataItem
				// console.log('status',status);
				// console.log('isStatus',isStatus);

				if (frozenReason && frozenReason.trim() !== '') {
					return selectDictLabel(this.orderStatus, '18');
				}
			
				let s = String(status);
				const is1 = String(isStatus) === '1';
				const is2 = String(isStatus) === '2';
				const is3 = String(isStatus) === '3';
				
				if(exceptionType == 2 && s == 13) {
					return selectDictLabel(this.orderStatus, s, 'reserved1');
				}
				if(exceptionType == 2 && s == 14) {
					return selectDictLabel(this.orderStatus, s, 'reserved1');
				}
				// 农户订单状态
				if(this.theme === 'farmer'){
					console.log('isStatus',isStatus);
					console.log('111111',s);
					if (s === '6' && is2) {
						s = '8';
					}
					if (s === '6' && is3) {
						s = '8';
					}
					if (s === '7' && is1) {
						s = '8';
					}
					if (s === '8' && is2) {
						s = '8';
					}
					if (s === '9' && is1 && commentStar == null) {
						s = '8';
					}
					if (commentStar != null) {
						s = '9';
					}
					if (s === '17') {
						s = '1'
					}
				}
				
				 if (this.theme === 'farmer' && ['1', '2', '6', '7', '8'].includes(s)) {
					return selectDictLabel(this.orderStatus, s, 'reserved1');
				}
				// 如果status=4 && isStatus=2，使用10的字典值
				if (s === '4' && is2) {
					return selectDictLabel(this.orderStatus, '10');
				}
				// 走原逻辑
				return selectDictLabel(this.orderStatus, s);
				//抢单状态
				// return "待抢单";
			}
		},
		props: {
			inOrder: {
				type: Boolean,
				default: false
			},
			dataItem: {
				type: Object,
				default: () => ({})
			},
			orderStatus: {
				type: Array,
				default: () => ([])
			}
		},
		filters: {
			dateOnly(value) {
				return value ? value.split(' ')[0] : '-';
			}
		},
		methods: {
			selectDictLabel,
			addOrder(v) {
				if(!this.userInfo) {
					uni.showToast({
						title: '请先登录再查看！'
					})
					uni.$uv.route({
						url: '/pages/public/login',
					})
					return
				}
				uni.$uv.route({
					url: '/pages/taskDetail/index',
					params: {
						id: this.dataItem.id,
						orderLogId: this.dataItem.orderLogId,
						action: v
					}
				})
			},
			onUpdata() {
				// uni.navigateTo({
				// 	url: '/pages/progressUpload/index'
				// })
				uni.$uv.route({
					url: '/subPages/pages/progressUpload/index',
					params: {
						id: this.dataItem.id,
						orderLogId: this.dataItem.orderLogId
					}
				})
			},
			onReport() {
				uni.$uv.route({
					// url: '/pages/reportException/index',
					url: '/subPages/pages/exceptionList/index',
					params: {
						id: this.dataItem.id,
						orderLogId: this.dataItem.orderLogId,
						homeworkStartTime: this.dataItem.homeworkStartTime,
						dockingPeopleTime: this.dataItem.dockingPeopleTime
					}
				})
			},
			onCancel() {
				uni.$uv.route({
					url: '/subPages/pages/cancelOrder/index',
					params: {
						id: this.dataItem.id,
					}
				})
			},
			onSigin() {
				// this.$emit('onSigin', {
				// 	id: this.dataItem.id,
				// 	orderLogId: this.dataItem.orderLogId
				// })
				uni.$uv.route({
					url: '/subPages/pages/signIn/index',
					params: {
						id: this.dataItem.id,
						orderLogId: this.dataItem.orderLogId,
						address: this.dataItem.address,
						lng: this.dataItem.lng,
						lat: this.dataItem.lat
					}
				})
			},
			reStart() {
				this.$http.get('/cadre/orderException/continueTask/' + this.dataItem.id).then(res => {
					this.$emit('success')
				})
			},
			// 修改 
			onEdit() {
				uni.$uv.route({
					url: '/subPages/pages/bookOrder/index',
					params: {
						id: this.dataItem.id,
						homeworkType: this.dataItem.homeworkType,
						orderLogId: this.dataItem.orderLogId,
						isEdit: true
						// address: this.dataItem.address,
						// lng: this.dataItem.lng,
						// lat: this.dataItem.lat
					}
				})
			},
			// 支付
			handlePay() {
				this.$store.dispatch('payment/payAction', this.dataItem).then(res => {
					console.log('支付成功回调', res)
				}).catch(err => {
					console.log('支付失败回调', err)
				})
			},
			cancelPayment(outTradeNo) {
				this.$http.get('/cadre/highSeasOrder/payStatus', {
					params: {
						outTradeNo
					}
				}).then(res => {
					console.log('取消支付', res)
				})
			},
			paySuccess() {

			},
			submitPay() {
				//订单对象，从服务器获取
				var orderInfo = {
					"appid": "o3teo7Xv5JSlbXTloJodMobUUTOw", // 应用ID（AppID）
					// "partnerid": "MINI84054691851750924026", // 商户号（PartnerID）
					// "prepayid": "wx202254********************fbe90000", // 预支付交易会话ID
					"package": "prepay_id=wx261547068962489ed6e598dc60d60f0000", // 固定值
					"nonceStr": "r0CgFrjZ1oHGvrh7NV8JV1JwRkCQEMRm", // 随机字符串
					"timeStamp": "1750924027", // 时间戳（单位：秒）
					"paySign": "orDGQzWuG3y6XF4dPNiDNPbySITN6XyzdwEjnzyMjpCvyFRZ3jgAxaM7nKDQiulDV9UGaxgUtWweyAsqXts4UXLMDseyTnMluJug8QMEge9ns2WIorAHbji+wneRC2JXA08CnqYUMDm+3mJ1dPrhT6w0KEf64cKk0CQlDgyfuuTgw+A5DCI7CN3UdhQwA/9RCIU1JLhD0VNNpTElxl7/RrCqVI2YsVxbymyS3r0ZjRq1vIz+14IcAY7bA94lY9Gka9HtvX0U66UmkW2dUoHVd5Hl3huKg62tz8FlDJcamQh8afGWvUoztGNvCDszA5OteNJfEAGud4gJI5FlHKOt0Q==", // 签名，这里用的 MD5 签名
					signType: "RSA"
				};
				uni.getProvider({
					service: 'payment',
					success: function(res) {
						console.log(res.provider)
						if (res.provider.indexOf('wxpay') != -1) {
							wx.requestPayment({
								...orderInfo,
								success: function(res) {
									var rawdata = JSON.parse(res.rawdata);
									console.log("支付成功");
								},
								fail: function(err) {
									console.log('支付失败:' + JSON.stringify(err));
								}
							});
						}
					}
				});
			},
			handleAuth() {
				this.$emit('authEvent', this.dataItem)
			},
			// 抢单
			robOrder() {
				let _this = this;
				uni.showModal({
					title: '抢单提示',
					content: '您确定要抢接该订单吗？',
					success: function(res) {
						if (res.confirm) {
							let user = uni.getStorageSync('userInfo');
							//判断用户是否实名
							if (user.authStatus == "1") {
								//已实名
								//抢单操作
								uni.showLoading({
									title: '加载中'
								});
								let formData = {
									"flyerId": user.id,
									"orderId": _this.dataItem.id,
									"orderCode": _this.dataItem.orderCode
								}
								_this.$http
									.post("/cadre/assignOrder/grabOrder", {}, {
										data: JSON.stringify(formData)
									})
									.then((res) => {
										uni.hideLoading();
										if (res.code == "200") {
											uni.showToast({
												title: "抢单成功",
												duration: 2000,
												image: `${_this.$hd.baseUrl}/images/icon-success.png`
											});
											//页面跳转
											that.$emit('success')
										} else {
											uni.showToast({
												title: "抢单失败",
												duration: 2000,
												image: `${_this.$hd.baseUrl}/images/icon-fail.png`
											});
										}
									})
									.catch((err) => {
										console.log(err)
										_this.showToast();
									});
							}
						} else {
							//未实名
							uni.showModal({
								title: '抢单提示',
								content: '您还未完成飞手认证，请先前往完成认证再进行抢单！',
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '/subPages/pages/authInfo/index'
										});
									}
								}
							})
						}
					}
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.item-card {
		border-radius: 20rpx;

		.ti-img {
			width: 40rpx;
			height: 40rpx;
		}

		.jl-text {
			color: #4CA0FF;
		}
	}
</style>